package com.ruoyi.web.controller.eduManage;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.utils.StudentNoUtils;
import com.ruoyi.eduManage.domain.EduStudent;
import com.ruoyi.eduManage.service.IEduStudentService;
import com.ruoyi.eduManage.domain.EduClass;
import com.ruoyi.eduManage.service.IEduClassService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生信息Controller
 * 
 * @author ruoyi
 * @date 2025-10-26
 */
@RestController
@RequestMapping("/manage/student")
public class EduStudentController extends BaseController
{
    @Autowired
    private IEduStudentService eduStudentService;

    @Autowired
    private IEduClassService eduClassService;

    /**
     * 查询学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('manage:student:list')")
    @GetMapping("/list")
    public TableDataInfo list(EduStudent eduStudent)
    {
        startPage();
        List<EduStudent> list = eduStudentService.selectEduStudentList(eduStudent);
        // 处理性别字典映射
        for (EduStudent student : list) {
            if (student.getSex() != null) {
                student.setSex(com.ruoyi.eduManage.utils.EduDictUtils.getDictLabel("sys_user_sex", student.getSex()));
            }
            // 根据classId查询班级名称；未查到则回填为classId
            String className = null;
            String sid = student.getClassId();
            if (sid != null && !sid.isEmpty()) {
                // 优先按classCode匹配
                EduClass query = new EduClass();
                query.setClassCode(sid);
                List<EduClass> classes = eduClassService.selectEduClassList(query);
                if (classes != null && !classes.isEmpty()) {
                    className = classes.get(0).getClassName();
                } else {
                    // 尝试按numeric classId匹配
                    try {
                        Long cid = Long.valueOf(sid);
                        EduClass clazz = eduClassService.selectEduClassByClassId(cid);
                        if (clazz != null) {
                            className = clazz.getClassName();
                        }
                    } catch (NumberFormatException ignore) {}
                }
            }
            student.setClassName((className == null || className.isEmpty()) ? student.getClassId() : className);
        }
        return getDataTable(list);
    }

    /**
     * 导出学生信息列表
     */
    @PreAuthorize("@ss.hasPermi('manage:student:export')")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EduStudent eduStudent)
    {
        List<EduStudent> list = eduStudentService.selectEduStudentList(eduStudent);
        ExcelUtil<EduStudent> util = new ExcelUtil<EduStudent>(EduStudent.class);
        util.exportExcel(response, list, "学生信息数据");
    }

    /**
     * 获取学生信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('manage:student:query')")
    @GetMapping(value = "/{studentId}")
    public AjaxResult getInfo(@PathVariable("studentId") Long studentId)
    {
        EduStudent student = eduStudentService.selectEduStudentByStudentId(studentId);
        if (student != null) {
            String className = null;
            String sid = student.getClassId();
            if (sid != null && !sid.isEmpty()) {
                // 优先按classCode匹配
                EduClass query = new EduClass();
                query.setClassCode(sid);
                List<EduClass> classes = eduClassService.selectEduClassList(query);
                if (classes != null && !classes.isEmpty()) {
                    className = classes.get(0).getClassName();
                } else {
                    // 尝试按numeric classId匹配
                    try {
                        Long cid = Long.valueOf(sid);
                        EduClass clazz = eduClassService.selectEduClassByClassId(cid);
                        if (clazz != null) {
                            className = clazz.getClassName();
                        }
                    } catch (NumberFormatException ignore) {}
                }
            }
            student.setClassName((className == null || className.isEmpty()) ? student.getClassId() : className);
        }
        return success(student);
    }

    /**
     * 新增学生信息
     */
    @PreAuthorize("@ss.hasPermi('manage:student:add')")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EduStudent eduStudent)
    {
        // 新增校验
        // 根据学号学生姓名+班级
        EduStudent existStudent = new EduStudent();
        // 使用学生所在班级的classCode生成学号
        String classCode = eduStudent.getClassId().substring(0, 3); // 假设classId的前三位就是classCode
        eduStudent.setStudentNo(StudentNoUtils.generateStudentNo(classCode));
        //existStudent.setStudentNo(student.getStudentNo());
        existStudent.setStudentName(eduStudent.getStudentName());
        existStudent.setClassId(eduStudent.getClassId());
        existStudent.setDelFlag("0");
        List<EduStudent> existStudents = eduStudentService.selectEduStudentList(existStudent);
        if (existStudents != null && !existStudents.isEmpty()) {
            return error("学生已存在");
        }
        return toAjax(eduStudentService.insertEduStudent(eduStudent));
    }

    /**
     * 修改学生信息
     */
    @PreAuthorize("@ss.hasPermi('manage:student:edit')")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EduStudent eduStudent)
    {
        return toAjax(eduStudentService.updateEduStudent(eduStudent));
    }

    /**
     * 删除学生信息
     */
    @PreAuthorize("@ss.hasPermi('manage:student:remove')")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{studentIds}")
    public AjaxResult remove(@PathVariable Long[] studentIds)
    {
        return toAjax(eduStudentService.deleteEduStudentByStudentIds(studentIds));
    }
    
    /**
     * 导入学生数据
     */
    @PreAuthorize("@ss.hasPermi('manage:student:import')")
    @Log(title = "学生信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam(required = false) Long classId)
    {
        String fileName = file.getOriginalFilename();
        try
        {
            String result = eduStudentService.importStudent(file, fileName, classId);
            return AjaxResult.success(result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }
    
    /**
     * 下载导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<EduStudent> util = new ExcelUtil<>(EduStudent.class);
        util.importTemplateExcel(response, "学生信息模板");
    }
}
